package com.xukang.HMac_SHA1;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author z k
 */
public class HmacSHA1Utils {

    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";
    private static final char[] DIGITS = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };

    /**
     * 使用HmacSHA1对source字符串散列
     * @param source 要散列的字符串
     * @param key  密匙，在家哇中对应appSecret;
     * @return 返回散列后的字符串,16进制编码
     * @throws Exception
     */
    public static String encrypt(String source, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        byte[] keyBytes=key.getBytes(ENCODING);
        SecretKey secretKey = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(secretKey);
        byte[] text = source.getBytes(ENCODING);
        byte[] sign=mac.doFinal(text);
        return toHexString(sign);
    }

    /**
     * 将byte[]形式的数据转换成16进制数据
     * @param data 要转换的byte[]数据
     * @return 生成的16进制数据
     */
    public static String toHexString(byte[] data){
        int l = data.length;

        char[] out = new char[l << 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS[0x0F & data[i]];
        }
        return new String(out);
    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String key = "POST/registerReceive/sendZdxxappIdqdhx_fpzdAppsignAlgorithmHmac-SHA1timestamp2019-08-20 10:54:10";
        String key2 = "POST/registerReceive/sendZdxxappIdqdhx_appsignAlgorithmHmac-SHA1timestamp2019-08-19 09:57:00";
        String sec = encrypt(key, "qdhx_fpzd_register");
        System.out.printf(sec);



    }
}
